package cn.rocksolid.proxy.restful.agency;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.rocksolid.sport.agency.entity.AgencyEntity;
import cn.rocksolid.sport.agency.service.AgencyService;
import cn.rocksolid.sport.common.context.RockSolidContextHolder;
import cn.rocksolid.sport.common.error.RSE;
import cn.rocksolid.sport.common.http.R;
import cn.rocksolid.sport.common.utils.AssertUtils;

@RestController
@RequestMapping("agency/agency")
public class AgencyController {

  private final AgencyService agencyService;

  @Autowired
  public AgencyController(final AgencyService agencyService) {
    this.agencyService = agencyService;
  }

  /**
   * get
   */
  @GetMapping
  @RequiresPermissions("agency:agency:info")
  public Object get() {
    return R.ok().put("agency", agencyService.getById(RockSolidContextHolder.getContext().getAgencyId()));
  }

  /**
   * modify
   */
  @PostMapping
  @RequiresPermissions("agency:agency:modify")
  public Object modify(@RequestBody final AgencyEntity agencyEntity) {
    validator(agencyEntity);
    AgencyEntity agency = new AgencyEntity();
    agency.setId(RockSolidContextHolder.getContext().getAgencyId());
    agency.setLogo(agencyEntity.getLogo());
    agency.setTheme(agencyEntity.getTheme());
    agency.setAppearance(agencyEntity.getAppearance());
    agency.setLocale(agencyEntity.getLocale());
    agency.setSummary(agencyEntity.getSummary());
    agencyService.updateById(agency);
    return R.ok();
  }

  /**
   * validate agency
   */
  public void validator(AgencyEntity agencyEntity) {
    AssertUtils.isNotNull(agencyEntity, RSE.INVALID_PAYLOAD);
    AssertUtils.isNotNull(agencyEntity.getLogo(), RSE.INVALID_AGLOGO);
  }
}
